/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bgu.sonar.util.collections.obs;

import bgu.sonar.util.evt.EventListeners;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

/**
 *
 * @author bennyl
 */
public class ObservableMap<K, V> implements Map<K, V> {

    Map<K, V> delegate;
    EventListeners<MapListener<K, V>> listeners = (EventListeners) EventListeners.create(MapListener.class);

    public ObservableMap(Map<K, V> delegate) {
        this.delegate = delegate;
    }

    @Override
    public int size() {
        return delegate.size();
    }

    @Override
    public boolean isEmpty() {
        return delegate.isEmpty();
    }

    @Override
    public boolean containsKey(Object key) {
        return delegate.containsKey(key);
    }

    @Override
    public boolean containsValue(Object value) {
        return delegate.containsValue(value);
    }

    @Override
    public V get(Object key) {
        return delegate.get(key);
    }

    public EventListeners<MapListener<K, V>> getListeners() {
        return listeners;
    }

    @Override
    public V put(K key, V value) {
        V old = delegate.put(key, value);
        if (old != null) {
            listeners.fire().onValueRemoved(this, key, old);
        }
        listeners.fire().onValueAdded(this, key, value);
        return old;
    }

    @Override
    public V remove(Object key) {
        V i = delegate.remove(key);
        listeners.fire().onValueRemoved(this, (K) key, i);
        return i;
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {
        for (Entry<? extends K, ? extends V> p : m.entrySet()) {
            put(p.getKey(), p.getValue());
        }
    }

    @Override
    public void clear() {
        delegate.clear();
        listeners.fire().onMapCleared(this);
    }

    @Override
    public Set<K> keySet() {
        return delegate.keySet();
    }

    @Override
    public Collection<V> values() {
        return delegate.values();
    }

    @Override
    public Set<Map.Entry<K, V>> entrySet() {
        return delegate.entrySet();
    }

    @Override
    public boolean equals(Object o) {
        return delegate.equals(o);
    }

    @Override
    public int hashCode() {
        return delegate.hashCode();
    }

    public interface MapListener<K, V> {

        void onValueAdded(ObservableMap<K, V> src, K key, V value);

        void onValueRemoved(ObservableMap<K, V> src, K key, V value);

        void onMapCleared(ObservableMap<K, V> src);
    }
}
